//
//  PFPhotoCollectionViewController.m
//  PrintFamily
//
//  Created by edaihua on 16/2/28.
//  Copyright © 2016年 ___PrintFactory___. All rights reserved.
//

#import "PhotoPickerCollectionViewController.h"
#import "PhotoPickerCollectionViewLayout.h"
#import "PhotoPickerCollectionViewCell.h"
#import "PFPhotosManager.h"
#import "PFPhoto.h"
#import "PFPrintManager.h"
#import "PFCommonRectManager.h"
#import "UIImage+Crop.h"
#import "UILabel+PhotoCount.h"
#import "PhotoListTableViewController.h"

@import Photos;

@interface PhotoPickerCollectionViewController ()

@property (nonatomic, strong) PHFetchResult *photoFetchResult;
@property (nonatomic, strong) PhotoPickerCollectionViewLayout *layout;

@property (strong, nonatomic) IBOutlet UIButton *backButton;
@property (strong, nonatomic) IBOutlet UIButton *rightButton;

@property (strong, nonatomic) IBOutlet UILabel *titleLabel;
@property (nonatomic)         PhotoPrintType    type;

@end

@implementation PhotoPickerCollectionViewController

static NSString * const reuseIdentifier = @"Cell";

@synthesize photoFetchResult;
@synthesize selectedAssets;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.layout == nil) {
        self.layout = [[PhotoPickerCollectionViewLayout alloc] init];
        [self.collectionView setCollectionViewLayout:self.layout];
    }
    
    // Uncomment the following line to preserve selection between presentations
    self.clearsSelectionOnViewWillAppear = YES;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.backButton];
    
    // Register cell classes
    [self.collectionView registerClass:[PhotoPickerCollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
    
    self.type = [PFPrintManager getCurrentType];
    
    [self.titleLabel updateWithPhotoCount:self.selectedAssets.count type:self.type];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [self.titleLabel updateWithPhotoCount:self.selectedAssets.count];
}

#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showPhotoList"]) {
        PhotoListTableViewController* listController = segue.destinationViewController;
        listController.commonRectManager = self.rectManager;
        [listController.photosManager addSelectedPhotoToPrintDesk:self.selectedAssets rectManager:self.rectManager];
    }
}


#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.photoFetchResult.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PhotoPickerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    CGFloat scale     = [UIScreen mainScreen].scale;
    CGSize  cellSize  = self.layout.itemSize;
    CGSize targetSize = CGSizeMake(cellSize.width * scale, cellSize.height * scale);
    PHAsset *asset    = self.photoFetchResult[indexPath.row];
    
    [[PHImageManager defaultManager] requestImageForAsset:asset
                                               targetSize:targetSize
                                              contentMode:PHImageContentModeAspectFit
                                                  options:nil
                                            resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
    
                                                UIImage *croppedImage = [result getImageInCenterAtSize:targetSize];
                                                
                                                UIImageView* imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, cellSize.width, cellSize.height)];
                                                [imgView setImage:croppedImage];
                                                [imgView setContentMode:UIViewContentModeScaleToFill];
    
                                                for (UIView *view in [cell.contentView subviews]) {
                                                    [view removeFromSuperview];
                                                }
    
                                                [cell.contentView addSubview:imgView];
                                                CGFloat selectButtonWidth = 40.0;
                                                UIButton *selectButton = [[UIButton alloc] initWithFrame:CGRectMake(cellSize.width - selectButtonWidth, 0.0, selectButtonWidth, selectButtonWidth)];
                                                selectButton.tag = indexPath.row;
                                                [selectButton setImage:[UIImage imageNamed:@"un-selected"] forState:UIControlStateNormal];
                                                [selectButton setImage:[UIImage imageNamed:@"selected"] forState:UIControlStateSelected];
                                                [selectButton addTarget:self action:@selector(photoSelected:) forControlEvents:UIControlEventTouchUpInside];
                                                
                                                if([self.photosManager getPhotoByLocalIdentifier:asset.localIdentifier]) {
                                                    selectButton.selected = YES;
                                                } else {
                                                    selectButton.selected = NO;
                                                }
                                                
                                                [cell.contentView addSubview:selectButton];
                                                
    }];
    
    return cell;
}

#pragma mark <UICollectionViewDelegate>

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    
}

#pragma mark - selected photo handling
- (void)removeSelectedPhotoWithIndex:(NSInteger)index {
    [self.selectedAssets removeObject:self.photoFetchResult[index]];
    [self.titleLabel updateWithPhotoCount:self.selectedAssets.count type:self.type];
}

- (void)addSelectedPhotoWithIndex:(NSInteger)index {
    //PFPhoto *photo = [[PFPhoto alloc] initWithPHAsset:self.photoFetchResult[index] printType:[PFPrintManager getCurrentType] boarder:PhotoBoarder_White rectManager:self.rectManager];
    //[self.selectedPhotos addObject:photo];
    [self.selectedAssets addObject:self.photoFetchResult[index]];
    [self.titleLabel updateWithPhotoCount:self.selectedAssets.count type:self.type];
}


#pragma mark - button gesture
- (IBAction)tapConfirm:(id)sender {
    
    if (self.selectedAssets.count == 0) {
        [self presentViewController:[AppDelegate createAlertControllerWithMessage:@"请选择照片"] animated:YES completion:nil];
        ;
    } else {
        [self performSegueWithIdentifier:@"showPhotoList" sender:sender];
    }
}

- (void)photoSelected:(id)sender {
    UIButton* button = (UIButton*)sender;
    NSInteger index = button.tag;
    
    if (button.isSelected) {
        [self removeSelectedPhotoWithIndex:index];
        [button setSelected:NO];
    } else {
        [self addSelectedPhotoWithIndex:index];
        [button setSelected:YES];
    }
}

- (IBAction)backTapped:(id)sender {
    if (self.selectedAssets.count == 0) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        NSString *warningMsg = [NSString stringWithFormat:@"已经选择了%lu张照片,确定要退出？", self.selectedAssets.count];
        void (^alertHandler)(UIAlertAction*) = ^(UIAlertAction*_Nullable action) {
            [self.navigationController popViewControllerAnimated:YES];
        };
        
        [self presentViewController:[AppDelegate createAlertControllerWithMessage:warningMsg confirmHandler:alertHandler] animated:YES completion:nil];
    }
    
}

#pragma mark - synthethizer
- (PHFetchResult*)photoFetchResult {
    if (photoFetchResult == nil) {
        PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
        fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
        photoFetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
    }
    return photoFetchResult;
}

- (NSMutableArray*)selectedAssets {
    if (selectedAssets == nil) {
        selectedAssets = [[NSMutableArray alloc] init];
    }
    return selectedAssets;
}

@end
